package com.hjy.service;

import com.hjy.enums.RoleEnum;
import com.hjy.mapper.UserMapper;
import com.hjy.pojo.User;
import com.hjy.vo.ResponseVo;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

import static com.hjy.enums.ResponseEnum.*;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 注册
     */
    public ResponseVo<User> register(User user) {
        //username不能重复
        int countByUsername = userMapper.countByUsername(user.getUsername());
        if (countByUsername > 0) {
            return ResponseVo.error(USERNAME_EXIST);
        }

        //email不能重复
        int countByEmail = userMapper.countByEmail(user.getEmail());
        if (countByEmail > 0) {

            return ResponseVo.error(EMAIL_EXIST);
        }

        user.setRole(RoleEnum.CUSTOMER.getCode());
        //MD5摘要算法(Spring自带)
        user.setPassword(DigestUtils.md5DigestAsHex(
                user.getPassword().getBytes(StandardCharsets.UTF_8)
        ));
        //写入数据库
        int resultCount = userMapper.insertSelective(user);
        if (resultCount == 0) {
            return ResponseVo.error(ERROR);
        }
        return ResponseVo.success();
    }

    /**
     *  登录
     */
    public ResponseVo<User> login(String username ,String password){
        User user = userMapper.selectByUsername(username);
        if (user == null){
            return ResponseVo.error(USERNAME_ERROR);
        }else if (!user.getPassword().equalsIgnoreCase(
                DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8))
        )){
            return ResponseVo.error(PASSWORD_ERROR);
        }

        return ResponseVo.success();
    }

    private void error(){throw new RuntimeException(ERROR.getDesc());}
}
